import re
from rest_framework import serializers
from areas.models import Area
from users.models import Address


class AreaSerializer(serializers.ModelSerializer):
    """
    行政区划信息序列化器
    """
    class Meta:
        model = Area
        fields = ('id', 'name')


class AddressSerializier(serializers.ModelSerializer):
    # 接受前段传来的参数，还需要3个字段
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)

    # 制定返回数据不是id而是字符串
    province = serializers.StringRelatedField(label='省',read_only=True)
    city = serializers.StringRelatedField(label='市',read_only=True)
    district = serializers.StringRelatedField(label='区',read_only=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_title')



    def validate_mobile(self,value):
        if not re.match(r"^1[3-9]\d{9}$",value):
            return serializers.ValidationError("手机格式不对")

        return value


    def create(self, validated_data):
        # 添加user属性
        validated_data["user"]=self.context["request"].user
        address = super().create(validated_data)

        return address
